package com.kuaishou.locallife.open.api.common.utils;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kuaishou.locallife.open.api.KsLocalLifeApiException;

/**
 * @author jiangduo <jiangduo@kuaishou.com>
 * Created on 2023-06-27
 */
public class ShortLinkUtil {
    private static final Pattern OBJECT_ID_PATTERN = Pattern.compile("object_id=([^&]*)(&|$)");

    private ShortLinkUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 获取Object_id
     *
     * @param url
     * @return
     * @throws KsLocalLifeApiException
     */
    public static String getObjectId(String url) throws KsLocalLifeApiException {
        String paramInfo = shortUnCompress(url).getQuery();
        Matcher matcher = OBJECT_ID_PATTERN.matcher(paramInfo);
        if (!matcher.find()) {
            throw new KsLocalLifeApiException("object_id不存在,请检查url格式");
        }
        return matcher.group(1);
    }

    /**
     * 获取转换后的长链url
     *
     * @param shortUrl
     * @return
     * @throws KsLocalLifeApiException
     * @deprecated use {@link #getObjectId(String)} ()} instead.
     */
    @Deprecated
    public static URL shortUnCompress(String shortUrl) throws KsLocalLifeApiException {
        URI uri = create(shortUrl);
        URL url;
        HttpURLConnection conn = null;
        int status;
        try {
            url = uri.toURL();
            conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            status = conn.getResponseCode();
            if (status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER) {
                String newUrl = conn.getHeaderField("Location");
                url = new URL(newUrl);
            }
        } catch (MalformedURLException | IllegalArgumentException e) {
            throw new KsLocalLifeApiException("请检查url格式：" + uri);
        } catch (IOException e) {
            throw new KsLocalLifeApiException("请检查域名：" + uri.getHost(), e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        if (uri.toString().equals(url.toString())) {
            throw new KsLocalLifeApiException("链接失效");
        }
        return url;
    }

    /**
     * 创建url & 初步检查格式
     *
     * @param str
     * @return
     * @throws KsLocalLifeApiException
     */
    private static URI create(String str) throws KsLocalLifeApiException {
        URI uri;
        try {
            uri = URI.create(str); //基本格式验证
        } catch (IllegalArgumentException e) {
            throw new KsLocalLifeApiException("URL格式不合法" + str, e);
        }
        String scheme = uri.getScheme();
        if (scheme == null) {
            throw new KsLocalLifeApiException("URL格式不合法" + str);
        }
        scheme = scheme.toLowerCase(Locale.US);
        if (!("http".equals(scheme) || "https".equals(scheme))) {
            throw new KsLocalLifeApiException("Scheme格式不合法:" + uri.getScheme() + ", 应为\"http\"或者\"https\"");
        }
        return uri;
    }
}
